package cn.blunce.FileWriteRead;

import java.io.*;

/**
 * Created by Experiment on 2016/3/29 0029.
 */
public class MyWriteRead {
    public static void readFileByBytes(String filename){
        /**
         * read file by bytes:
         * by one byte and by some bytes
         *
         * Usage:read picture，voice,video
         *
         * Found in Android often.
         */
        File file = new File(filename);
        InputStream inputStream = null;
        try {
            //by one byte
            inputStream = new FileInputStream(file);
            int tmpbyte;
            while ((tmpbyte=inputStream.read())!=-1){
                System.out.write(tmpbyte);
            }
            inputStream.close();
        }catch (IOException e){
            e.printStackTrace();
            return;
        }

        try {
            //by some bytes
            byte[] tmpbytes = new byte[100];
            int byteread = 0;
            inputStream = new FileInputStream(file);
            while ((byteread=inputStream.read(tmpbytes))!=-1){
                System.out.write(tmpbytes,0,byteread);
            }
            inputStream.close();
        }catch (IOException e){
            e.printStackTrace();
            return;
        }
    }

    public static void readFileByChars(String filename){
        /**
         *
         */
        File file = new File(filename);
        Reader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream(file));
            int tmpchar ;
            while ((tmpchar=reader.read())!=-1){
                System.out.println((char)tmpchar);
            }
            reader.close();
        }catch (IOException e){
            e.printStackTrace();;
            return;
        }
    }

    /**
     * read file by lines
     *
     */
    public static void readFileByLines(String fileName){
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            while ((tempString = reader.readLine()) != null){
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
}
